package com.yupi.springbootinit.utils;/*
@author name
@data 2025/2/10-22:17
*/

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Excel 转csv 工具类
 */
@Slf4j
public class ExcelUtils {
    public static String ExcelToCsv(MultipartFile multipartFile){
        List<Map<Integer,String>> list = null;

        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                   .excelType(ExcelTypeEnum.XLSX)
                   .sheet()
                   .headRowNumber(0)
                   .doReadSync();
        } catch (IOException e) {
           log.error("表格处理错误",e);
        }

        if(CollUtil.isEmpty(list)){
            return null;
        }
        //获取表头第一行
        StringBuilder stringBuilder = new StringBuilder();

        Map<Integer, String> map = list.get(0);
        List<String> stringList = map.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
        stringBuilder.append(StringUtils.join(stringList,",")).append("\n");
        log.info("开始输出csv内容");
        System.out.println(StringUtils.join(stringList,","));
        //获取表内容
        for(int i = 1;i < list.size();i++){
            Map<Integer, String> detailMao = list.get(i);
            List<String> detailList = detailMao.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
            stringBuilder.append(StringUtils.join(detailList,",")).append("\n");
            System.out.println(StringUtils.join(detailList,","));
        }
        return stringBuilder.toString();
    }
}






























